package com.study.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.study.pojo.User;

@Controller
public class uploadController {
	
	@RequestMapping("/upload")
	public String upload(HttpServletRequest request, HttpServletResponse response){
		
		return "upload";
	}
	
	@RequestMapping("/onlyUploadFile")
	public String onlyUploadFile(Model model ,
			@RequestParam("file") CommonsMultipartFile[] files,
			HttpServletRequest request,
			HttpServletResponse response){
		for(int i=0; i<files.length; i++){
			/*FileItem fileItem = files[i].getFileItem();
			String filename = files[i].getName();
			String fileOriginalName = files[i].getOriginalFilename();
			String contenType = files[i].getContentType();
			long size = files[i].getSize();*/
			try {
				//上传到WEB-INF下的uploadFiles目录下
				String path = request.getServletContext().getRealPath("/")+"uploadFiles";
				//如果uploadFiles不存在，则创建
				File savefile = new File(path);
				if(!savefile.exists()){
					savefile.mkdirs();
				}
				
				//重命名文件名字
				String name = files[i].getOriginalFilename();
				if(name.equals("") || name == null){
					continue;
				}
				int index = name.lastIndexOf('.');
				String preFileName = name.substring(0, index)+new SimpleDateFormat("_HHmmssSSS").format(new Date());
				String sufFileName = name.substring(index, name.length());
				String rename = preFileName+sufFileName;
				
				File pathFile = new File(savefile+"/"+rename);
				
				files[i].transferTo(pathFile);
			} catch (Exception e) {
				model.addAttribute("message", "上传失败!");
				return "fail";
			}
			
		}
		model.addAttribute("message", "上传成功!");
		return "success";
	}
	
	@RequestMapping("/allUpload")
	public String allUpload(Model model,
			User user,
			@RequestParam("file") CommonsMultipartFile[] files,
			HttpServletRequest request,
			HttpServletResponse response){
		
		System.out.println(user.toString());
		
		new uploadController().onlyUploadFile(model, files, request, response);
		
		model.addAttribute("message", "上传成功!");
		return "success";
	}
}
